package com.multysite.controller.admin;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.multysite.entity.admin.Application;
import com.multysite.entity.admin.ApplicationConfig;
import com.multysite.model.admin.ApplicationConfigModel;
import com.multysite.model.admin.ApplicationModel;
import com.multysite.util.Setting;

@SuppressWarnings("serial")
public class EditApplicationServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(EditApplicationServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			String siteTitle = req.getParameter("siteTitle");
			String siteDescription = req.getParameter("siteDescription");
			String siteKeyword = req.getParameter("siteKeyword");
			if (!NamespaceManager.get().equals(Setting.getGeneralNamespace())) {
				User user = UserServiceFactory.getUserService()
						.getCurrentUser();
				Application app = ApplicationModel.getById(NamespaceManager
						.get());
				if (app != null && user != null
						&& user.getEmail().equals(app.getUserEmail())) {
					NamespaceManager.set(app.getId());
					ApplicationConfig config = ApplicationConfigModel.getById(
							NamespaceManager.get(), NamespaceManager.get());					
					config.setTitle(siteTitle);
					config.setDescription(siteDescription);
					config.setKeyword(siteKeyword);
					ApplicationConfigModel.insert(NamespaceManager.get(),
							config);
					resp.sendRedirect("/admin");
				} else {
					resp.getWriter().println("Invalid Permission");
				}
			} else {
				resp.getWriter().println("Invalid Url");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.warning(e.toString());
			resp.sendError(4000,
					"Website is down for maintenance. We are sorry for the inconvenience !");
		}
	}
}
